package com.example.linearlayoutdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.linearlayoutdemo.bindservice.GpsService;

public class GpsActivity extends AppCompatActivity {
    private GpsService gpsService;
    private boolean isBound = false;
    private TextView tv_result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_gps);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        tv_result = findViewById(R.id.tv_gps);
    }

    // 绑定 Service 的连接对象
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取 Service 实例
            GpsService.GpsBinder binder = (GpsService.GpsBinder) service;
            gpsService = binder.getService();
            isBound = true;

            // 注册回调，接收 GPS 数据
            gpsService.setGpsCallback((lat, lon, timestamp) -> {
                // 主线程更新 UI（如地图定位点）
                runOnUiThread(() -> updateMapLocation(lat, lon));
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        // 绑定 Service
        Intent intent = new Intent(this, GpsService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 解绑 Service（避免内存泄漏）
        if (isBound) {
            gpsService.setGpsCallback(null); // 清除回调引用
            unbindService(connection);
            isBound = false;
        }
    }

    // 更新地图位置（示例）
    private void updateMapLocation(double lat, double lon) {
        // ... 刷新地图逻辑
        tv_result.setText("(" +lat + "," + lon +")");
    }
}